<template>
  <div class="factory-content">
    <Checkbox v-model="single"  @on-change='onChange'    style="margin-left:20px">全国</Checkbox>
    <Tree :data="areaListFilter" @on-check-change="onCheckChange" show-checkbox multiple></Tree>
    <Loader :status="status" @refresh="getData"></Loader>
  </div>
</template>
<script>
import { getOriginData } from "@/util";
export default {
  props: {
    hasDepartmentData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      departments: [],
      status: "pass",
      single: false
    };
  },
  created() {
    this.getData();
  },
  computed: {
   
    areaListFilter() {
      let val = getOriginData(this.departments);
      if (this.single === true) {
        const ck = arr => {
          arr.forEach(item => {
            item.value = item.id;
            item.label = item.name;
            item.title = item.name;
            item.disabled = true;
            if (this.hasDepartmentData.find(i => i == item.id)) {
              item.checked = true;
            } else {
              item.checked = false;
            }
            if (item.children && item.children.length) {
              ck(item.children);
            }
          });
        };
        // this.single = true;
        ck(val);
      } else {
        const ck = arr => {
          arr.forEach(item => {
            item.value = item.id;
            item.label = item.name;
            item.title = item.name;
            if (this.hasDepartmentData.find(i => i == item.id)) {
              item.checked = true;
            } else {
              item.checked = false;
            }
            if (item.children && item.children.length) {
              ck(item.children);
            }
          });
        };
        // this.single = false;
        ck(val);
      }

      return val;
    }
  },
  methods: {
    getData() {
      this.status = "loading";
      this.$jsonPost("/department/listDepartmentTree")
        .then(res => {
          this.departments = res;
          this.status = "pass";
        })
        .catch(err => {
          this.status = "error";
        });
    },
    onCheckChange(value) {
      this.$emit("onCheckChange", value);
    },
    onChange(single) {
      this.$emit("onChange", single);
    }
  },
  watch:{
    hasDepartmentData(){
      if(this.hasDepartmentData[0]==='0'){
        this.single=true
      }
    },
    immediate: true
  }
  
};
</script>
